<template>
  <el-row :gutter="20">
    <el-col v-for="(item,index) in prodList" :span="6">
      <el-card style="max-width: 480px">
        <template #header>
          <div class="card-header">
            <span>{{item.name}}</span>
          </div>
        </template>
        <el-image :src="'https://omsv2-static.fnji.com/'+item.picLeft" alt=""/>
        <template #footer>
          <el-popconfirm title="确定不是手抖?" @confirm="handleDel(item.objectId,index)">
            <template #reference>
              <el-button type="danger" size="small">
                删除
              </el-button>
            </template>
          </el-popconfirm>
          
          <el-button type="primary" size="small" @click="handleUpdate(item,index)">
            编辑
          </el-button>
          
          
        </template>
      </el-card>
    </el-col>
  </el-row>

  <!-- 编辑弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    title="Tips"
    width="500"
  >
    <el-input v-model="goodName"  placeholder="Please input" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleGoodPut">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import request from '../../utils/request.js'

const prodList = ref([]) //1.定数据
// Promise语法
request.get('/classes/product').then(res=>{
  console.log(res);
  prodList.value = res.data.results 
})

//删除商品
const handleDel = async (id,i)=>{
  console.log('确认删除');
  // 1. 删除数据库中的数据（需要objectId）
  await request.delete(`/classes/product/${id}`)

  // 2. 删除本地prodList中的数据包
  prodList.value.splice(i,1)
  
}

// 编辑商品信息
const dialogVisible = ref(false)
const goodName = ref('默认名称')  //编辑弹窗输入框内容
const id = ref('')  //记录待更新的商品objectId
const updateIdx = ref('') //记录待更新的商品序号
//编辑按钮
const handleUpdate = (item,idx)=>{
  dialogVisible.value = true
  goodName.value = item.name
  id.value = item.objectId
  updateIdx.value = idx
}
//弹窗确认按钮
const handleGoodPut = async ()=>{
  // 1. 更新数据库
  await request.put(`/classes/product/${id.value}`,{
    name:goodName.value   //键名必须跟数据库中想要更新的字段保持一致
  })

  // 2. 更新本地数据包prodList
  prodList.value[updateIdx.value].name = goodName.value

  // 3. 关闭弹窗
  dialogVisible.value = false
}
</script>

<style lang="scss" scoped>
.el-col{
  margin-bottom: 20px;
}
</style>